package service

import (
	"awesomeProject/app/model"
	"awesomeProject/app/response"
	"awesomeProject/global"
	"awesomeProject/util"
	"encoding/json"
	"fmt"
	//"strconv"
	"strings"
)

type ShopSrv struct{}

func (s *ShopSrv) QueryMap(shopIds []uint, companyId uint, operator model.User) response.Resp {
	exCompanyIds := operator.ExCompanyIds
	if operator.ExCompanyIds == "" {
		exCompanyIds = "0"
	}
	where := "shop_id<>0"
	var companies []model.Company
	if companyId != 0 {
		if companyId == global.OtherCompanyID {  // 其他组织
			_ = global.Gorm.Where(fmt.Sprintf(" `id`<>%d and `id` in (%s)", global.OtherCompanyID, exCompanyIds)).Limit(1).Find(&companies).Error
			where += fmt.Sprintf(" and `company_id` in (%s)", exCompanyIds)
		} else if companyId == global.MainCompanyID {  // 主组织
			_ = global.Gorm.Where(fmt.Sprintf(" `id`=%d", operator.CompanyId)).Limit(1).Find(&companies).Error
			where += fmt.Sprintf(" and `company_id`=%d", operator.CompanyId)
		} else {
			_ = global.Gorm.Where("`id`=?", companyId).Find(&companies).Error
			where += fmt.Sprintf(" and `company_id`=%d", companyId)
		}
	} else {
		//_ = global.Gorm.Find(&companies).Error
		companyIds := util.GetUserCompanyIds(operator)
		order := "id asc"
		if len(companyIds) > 0 {
			order = "field(`id`," + util.UintsToStr(companyIds, ",") + ")"
			_ = global.Gorm.Where(fmt.Sprintf("`id` in (%s)", util.UintsToStr(companyIds, ","))).Order(order).Find(&companies).Error
			where += fmt.Sprintf(" and `company_id` in (%s)", util.UintsToStr(companyIds, ","))
		} else {
			_ = global.Gorm.Order(order).Find(&companies).Error
		}
	}
	//companiesMap := map[uint]model.Company{}
	//for _, company := range companies {
	//	companiesMap[company.ID] = company
	//}

	//user := userSrv.FindByID(operator.ID, operator.CompanyId)
	if !operator.SuperAdmin {
		if len(shopIds) > 0 {
			shopIds = util.IntersectUIntArray(operator.ShopIds, shopIds)
		} else {
			shopIds = operator.ShopIds
		}
	}
	if len(shopIds) > 0 {
		b, _ := json.Marshal(shopIds)
		var shopIdStr = string(b)
		shopIdStr = strings.Trim(shopIdStr, "[]")
		where += fmt.Sprintf(" and `shop_id` in (%s)", shopIdStr)
	}
	var accounts []model.Account
	err := global.Gorm.Where("`status`=? and fordeal_shop_name!=''", 1).Where(where).
		Order("fordeal_shop_name").Find(&accounts).Error
	if err != nil {
		return response.ErrQuery
	}
	//for i, account := range accounts {
	//	accounts[i].CompanyName = companiesMap[uint(account.CompanyId)].CompanyName
	//}

	if companyId == global.OtherCompanyID {  // 其他组织
		for k, _ := range companies {
			companies[k].ID = global.OtherCompanyID
			companies[k].CompanyName = global.OtherCompanyName
		}
	} else if companyId == global.MainCompanyID {  // 主组织
		for k, _ := range companies {
			companies[k].ID = global.MainCompanyID
			companies[k].CompanyName = global.MainCompanyName
		}
	} else if companyId == 0 {  // 全部
		if !operator.SuperAdmin && operator.ID != global.SuperAdminUserID {
			for k, _ := range companies {
				companies[k].ID = global.MainCompanyID
				companies[k].CompanyName = global.MainCompanyName
			}
		}
	}

	var companiesMap map[uint]string
	companiesMap = make(map[uint]string)
	if len(companies) > 0 {
		for _, company := range companies {
			companiesMap[uint(company.ID)] = company.CompanyName
		}
	}
	if len(accounts) > 0 {
		for k, account := range accounts {
			if companyId == global.OtherCompanyID {  // 其他组织
				accounts[k].CompanyId = global.OtherCompanyID
				accounts[k].CompanyName = global.OtherCompanyName
			} else if companyId == global.MainCompanyID {  // 主组织
				accounts[k].CompanyId = global.MainCompanyID
				accounts[k].CompanyName = global.MainCompanyName
			} else {
				accounts[k].CompanyName = companiesMap[uint(account.CompanyId)]
			}
		}
	}

	if !operator.SuperAdmin && operator.ID != global.SuperAdminUserID {
		if len(companies) > 1 {
			companies = companies[:2]
			companies[0].ID = global.MainCompanyID
			companies[0].CompanyName = global.MainCompanyName // 主组织

			companies[1].ID = global.OtherCompanyID
			companies[1].CompanyName = global.OtherCompanyName // 其他组织
		} else {
			companies = companies[:1]
			companies[0].ID = global.MainCompanyID
			companies[0].CompanyName = global.MainCompanyName // 主组织
		}

		if len(accounts) > 0 && companyId != global.OtherCompanyID && companyId != global.MainCompanyID {
			for k, _ := range accounts {
				if accounts[k].CompanyId == operator.CompanyId {  // 主组织
					accounts[k].CompanyId = global.MainCompanyID
					accounts[k].CompanyName = global.MainCompanyName
				} else {  // 其他组织
					accounts[k].CompanyId = global.OtherCompanyID
					accounts[k].CompanyName = global.OtherCompanyName
				}
			}
		}
	}

	return response.OK.WithData(map[string]interface{}{
		"shops":     accounts,
		"companies": companies,
	})
}

func (s *ShopSrv) QueryMapFull(shopIds []uint, companyId uint, operator model.User) response.Resp {
	exCompanyIds := operator.ExCompanyIds
	if operator.ExCompanyIds == "" {
		exCompanyIds = "0"
	}
	where := "shop_id<>0"
	var companies []model.Company
	if companyId != 0 {
		if companyId == global.OtherCompanyID {  // 其他组织
			_ = global.Gorm.Where(fmt.Sprintf(" `id`<>%d and `id` in (%s)", global.OtherCompanyID, exCompanyIds)).Limit(1).Find(&companies).Error
			where += fmt.Sprintf(" and `company_id` in (%s)", exCompanyIds)
		} else if companyId == global.MainCompanyID {  // 主组织
			_ = global.Gorm.Where(fmt.Sprintf(" `id`=%d", operator.CompanyId)).Limit(1).Find(&companies).Error
			where += fmt.Sprintf(" and `company_id`=%d", operator.CompanyId)
		} else {
			_ = global.Gorm.Where("`id`=?", companyId).Find(&companies).Error
			where += fmt.Sprintf(" and `company_id`=%d", companyId)
		}
	} else {
		//_ = global.Gorm.Find(&companies).Error
		companyIds := util.GetUserCompanyIds(operator)
		order := "id asc"
		if len(companyIds) > 0 {
			order = "field(`id`," + util.UintsToStr(companyIds, ",") + ")"
			_ = global.Gorm.Where(fmt.Sprintf("`id` in (%s)", util.UintsToStr(companyIds, ","))).Order(order).Find(&companies).Error
			where += fmt.Sprintf(" and `company_id` in (%s)", util.UintsToStr(companyIds, ","))
		} else {
			_ = global.Gorm.Order(order).Find(&companies).Error
		}
	}

	//user := userSrv.FindByID(operator.ID, operator.CompanyId)
	if !operator.SuperAdmin {
		if len(shopIds) > 0 {
			shopIds = util.IntersectUIntArray(operator.ShopIds, shopIds)
		} else {
			shopIds = operator.ShopIds
		}
	}
	if len(shopIds) > 0 {
		b, _ := json.Marshal(shopIds)
		var shopIdStr = string(b)
		shopIdStr = strings.Trim(shopIdStr, "[]")
		where += fmt.Sprintf(" and `shop_id` in (%s)", shopIdStr)
	}
	var accounts []model.Account
	err := global.Gorm.Where("1=1 and fordeal_shop_name!=''").Where(where).
		Order("fordeal_shop_name").Find(&accounts).Error
	if err != nil {
		return response.ErrQuery
	}
	//global.LoggerOut(where)

	if companyId == global.OtherCompanyID {  // 其他组织
		for k, _ := range companies {
			companies[k].ID = global.OtherCompanyID
			companies[k].CompanyName = global.OtherCompanyName
		}
	} else if companyId == global.MainCompanyID {  // 主组织
		for k, _ := range companies {
			companies[k].ID = global.MainCompanyID
			companies[k].CompanyName = global.MainCompanyName
		}
	} else if companyId == 0 {  // 全部
		if !operator.SuperAdmin && operator.ID != global.SuperAdminUserID {
			for k, _ := range companies {
				companies[k].ID = global.MainCompanyID
				companies[k].CompanyName = global.MainCompanyName
			}
		}
	}

	var companiesMap map[uint]string
	companiesMap = make(map[uint]string)
	if len(companies) > 0 {
		for _, company := range companies {
			companiesMap[uint(company.ID)] = company.CompanyName
		}
	}
	if len(accounts) > 0 {
		for k, account := range accounts {
			if companyId == global.OtherCompanyID {  // 其他组织
				accounts[k].CompanyId = global.OtherCompanyID
				accounts[k].CompanyName = global.OtherCompanyName
			} else if companyId == global.MainCompanyID {  // 主组织
				accounts[k].CompanyId = global.MainCompanyID
				accounts[k].CompanyName = global.MainCompanyName
			} else {
				accounts[k].CompanyName = companiesMap[uint(account.CompanyId)]
			}
		}
	}

	if !operator.SuperAdmin && operator.ID != global.SuperAdminUserID {
		if len(companies) > 1 {
			companies = companies[:2]
			companies[0].ID = global.MainCompanyID
			companies[0].CompanyName = global.MainCompanyName // 主组织

			companies[1].ID = global.OtherCompanyID
			companies[1].CompanyName = global.OtherCompanyName // 其他组织
		} else {
			companies = companies[:1]
			companies[0].ID = global.MainCompanyID
			companies[0].CompanyName = global.MainCompanyName // 主组织
		}

		if len(accounts) > 0 && companyId != global.OtherCompanyID && companyId != global.MainCompanyID {
			for k, _ := range accounts {
				if accounts[k].CompanyId == operator.CompanyId {  // 主组织
					accounts[k].CompanyId = global.MainCompanyID
					accounts[k].CompanyName = global.MainCompanyName
				} else {  // 其他组织
					accounts[k].CompanyId = global.OtherCompanyID
					accounts[k].CompanyName = global.OtherCompanyName
				}
			}
		}
	}

	return response.OK.WithData(map[string]interface{}{
		"shops":     accounts,
		"companies": companies,
	})
}

func (s *ShopSrv) QueryShopIdsByUser(user model.User) (error, []uint) {
	//companyId := user.CompanyId
	var shopIds []uint
	var accounts []model.Account
	where := "status=1 and shop_id<>0"
	//if companyId != 0 {
	//	where += " and `company_id`=" + strconv.Itoa(int(companyId))
	//}
	companyIds := util.GetUserCompanyIds(user)
	if len(companyIds) > 0 {
		where += fmt.Sprintf(" and `company_id` in (%s)", util.UintsToStr(companyIds, ","))
	}
	err := global.Gorm.Where(where).Find(&accounts).Error
	if err != nil {
		return err, shopIds
	}
	for _, account := range accounts {
		shopIds = append(shopIds, account.ShopId)
	}

	return nil, shopIds
}

func (s *ShopSrv) QueryShopIdsByUserFull(user model.User) (error, []uint) {
	//companyId := user.CompanyId
	var shopIds []uint
	var accounts []model.Account
	where := "shop_id<>0"
	//if companyId != 0 {
	//	where += " and `company_id`=" + strconv.Itoa(int(companyId))
	//}
	companyIds := util.GetUserCompanyIds(user)
	if len(companyIds) > 0 {
		where += fmt.Sprintf(" and `company_id` in (%s)", util.UintsToStr(companyIds, ","))
	}
	err := global.Gorm.Where(where).Find(&accounts).Error
	if err != nil {
		return err, shopIds
	}
	for _, account := range accounts {
		shopIds = append(shopIds, account.ShopId)
	}

	return nil, shopIds
}

// UserShops 用户店铺权限
func (s *ShopSrv) UserShops(uid uint, operator model.User) response.Resp {
	user := userSrv.FindByID(uid, operator.CompanyId)
	if user.ID == 0 {
		return response.ErrRecordNotFound
	}
	where := "1=1"
	//if user.CompanyId > 0 {
	//	where += fmt.Sprintf(" and company_id=%d", user.CompanyId)
	//}
	companyIds := util.GetUserCompanyIds(user)
	if len(companyIds) > 0 {
		where += fmt.Sprintf(" and `company_id` in (%s)", util.UintsToStr(companyIds, ","))
	}

	var accounts []model.AccountWithChecked
	//err := global.Gorm.Where("`status` = ? and `fordeal_shop_name` != ''", 1).
	//	Where(where).Order("fordeal_shop_name").Find(&accounts).Error
	err := global.Gorm.Where("`fordeal_shop_name`!=''").
		Where(where).Order("fordeal_shop_name").Find(&accounts).Error
	if err != nil {
		return response.ErrQuery
	}
	for i, account := range accounts {
		if util.Contains(user.ShopIds, account.ShopId) {
			accounts[i].Checked = true
		}
	}
	return response.OK.WithData(accounts)
}
